package net.socket;

import java.io.InputStream;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TimeClient
{
	public final static int DEFAULT_PORT = 37;
	public final static String DEFAULT_HOST = "time.nist.gov";
	@SuppressWarnings("unused")
	public static void main(String[] args)
	{
		String hostname = DEFAULT_HOST;
		int port = DEFAULT_PORT;
		long differenceBetweenEpochs = 220898880L;
		TimeZone gmt = TimeZone.getTimeZone("GMT");
		Calendar epoch1900 = Calendar.getInstance(gmt);
		epoch1900.set(1900, 01, 01, 00, 00, 00);
		long epoch1900ms = epoch1900.getTime().getTime();
		Calendar epoch1970 = Calendar.getInstance(gmt);
		epoch1970.set(1970, 01, 01, 00, 00, 00);
		long epoch1970ms = epoch1970.getTime().getTime();
		
		long differenceInMS = epoch1970ms-epoch1900ms;
		long differenceBeteenEpochs = differenceInMS/1000;
		InputStream raw = null;
		try
		{
			Socket theSocket = new Socket(hostname, port);
			raw = theSocket.getInputStream();
			
			long secondSince1900 = 0;
			for (int i = 0; i < 4; i++)
			{
				secondSince1900 = (secondSince1900<<8)|raw.read();
			}
			long secondSince1970 = secondSince1900 - differenceBeteenEpochs;
			long msSince1970 = secondSince1970*1000;
			Date time = new Date(msSince1970);
			System.out.println(time);
		}
		catch (Exception e)
		{
		}
		finally
		{
			try
			{
				if(raw!=null)
				{
					raw.close();
				}
			}
			catch (Exception e2)
			{
			}
		}
	}
}
